package cn.tannn.cat.file.server.service.impl;

import cn.tannn.cat.file.server.controller.manage.dto.DictSortEdit;
import cn.tannn.cat.file.server.dao.DictDao;
import cn.tannn.cat.file.server.entity.Dict;
import cn.tannn.cat.file.server.enums.DictStatus;
import cn.tannn.cat.file.server.enums.DictType;
import cn.tannn.cat.file.server.service.DictService;
import cn.tannn.jdevelops.exception.built.BusinessException;
import cn.tannn.jdevelops.jpa.service.J2ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 字典
 *
 * @author <a href="https://tannn.cn/">tan</a>
 * @date 2024/3/7 14:21
 */
@Slf4j
@Service
public class DictServiceImpl extends J2ServiceImpl<DictDao, Dict, Long> implements DictService {
    public DictServiceImpl() {
        super(Dict.class);
    }

    @Override
    public void enables(List<Long> ids) {
        getJpaBasicsDao().updateState(ids, DictStatus.ENABLE);
    }

    @Override
    public void disable(List<Long> ids) {
        getJpaBasicsDao().updateState(ids, DictStatus.DISABLE);
    }

    @Override
    public void sort(DictSortEdit sort) {
        getJpaBasicsDao().updateSort(sort);
    }

    @Override
    public void append(Dict dict) {
        if (exist(dict.getValue(), dict.getDictType())) {
            throw new BusinessException("当前字典已存在请勿重复添加");
        }
        getJpaBasicsDao().save(dict);
    }

    @Override
    public List<Dict> fileDict() {
        return getJpaBasicsDao().findByDictTypeAndStatus(DictType.FILE_STORAGE
                , DictStatus.ENABLE
                , Sort.by("sort").ascending());
    }

    @Override
    public Optional<Dict> findDict(String value, DictType dictType) {
        return getJpaBasicsDao().findByValueAndDictType(value, dictType);
    }

    /**
     * 查重
     *
     * @param value    值
     * @param dictType 类型
     * @return true 存在
     */
    boolean exist(String value, DictType dictType) {
        return getJpaBasicsDao().findByValueAndDictType(value, dictType).isPresent();
    }


}
